package com.snail.poker.web.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.snail.poker.uitls.DateUtil;

/**
 * 从客户端请求服务数据的日志拦截器
 * 
 * @author Snail
 * 
 */
public class LogInterceptor extends AbstractInterceptor {
	private final static Log log = LogFactory.getLog(LogInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		log.warn("******************** 请求服务开始 ********************");
		log.warn("......开始执行登录Action的时间:" + DateUtil.getDate() + ".......");
		// 取得开始执行Action的时间
		long start = System.currentTimeMillis();

		String method = invocation.getProxy().getMethod();
		log.warn("请示服务处理方法："
				+ (StringUtils.isBlank(method) ? "method" : method));

		// 截取请求URL
		HttpServletRequest request = (HttpServletRequest) invocation
				.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
		String currentURL = request.getRequestURI();
		String targetURL = "";
		if (-1 != currentURL.indexOf("?")) {
			// 普通<form>标签是?分隔传来的参数
			String paramURL = currentURL.substring(currentURL.indexOf("?", 0),
					currentURL.length());// 参数URL
			int targetLength = currentURL.length() - paramURL.length();// 去掉请求参数Length
			targetURL = currentURL.substring(currentURL.indexOf("/", 1),
					targetLength);
			log.warn("去掉请求参数路径URL：" + targetURL);
		} else if (-1 != currentURL.indexOf(";")) {
			// struts2标签<s:form>标签是;分隔传来的参数
			String paramURL = currentURL.substring(currentURL.indexOf(";", 0),
					currentURL.length());// 参数URL
			int targetLength = currentURL.length() - paramURL.length();// 去掉请求参数Length
			targetURL = currentURL.substring(currentURL.indexOf("/", 1),
					targetLength);
			log.warn("去掉请求参数路径URL:" + targetURL);
		} else {
			targetURL = currentURL.substring(currentURL.indexOf("/", 1),
					currentURL.length());
			log.warn("请求路径URL:" + targetURL);
		}

		Map<String, Object> param = invocation.getInvocationContext()
				.getParameters();
		for (Map.Entry<String, Object> map : param.entrySet()) {
			String key = map.getKey();
			String[] values = (String[]) map.getValue();
			for (String val : values) {
				log.warn("请求参数关键字：" + key + "   请求参数值：" + val);
			}
		}
		String result = invocation.invoke();
		// 打印执行结束的时间
		log.warn("......执行结果：" + result + ".......");
		log.warn("......执行完登录Action的时间:" + DateUtil.getDate() + ".......");
		long end = System.currentTimeMillis();
		log.warn("......执行完该Action的事件为:" + (end - start) + "毫秒.......");
		log.warn("******************** 请求服务结束 ********************\n");
		return result;
	}
}
